package com.RequestGongWuShu;

import java.io.File;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.requestGwsLongGangQu.GwsLgqUtil;
import com.yishun.springboot.pojo.RequestGongWuShuTspBaseInfo;
import com.yishun.springboot.pojo.RequestGongWuShuTspRealTimeData;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 环境监测设备对接测试 注：方法上的注释打√的方法为对接测试环境已通过 @date 2020/12/04 16:04 √√的为对接测试环境正式数据已通过
 * 2020/12/12 开始改装：将该类主要业务方法变为传参的各类方法！（正式数据） @date 2020/12/08 14:15
 *
 * @author YS
 */

@Slf4j
public class envMonitoring {

	private String api_key = "08a44b1d310143b7911a3a54d33136b4";
	private String api_version = "1.0";
	private String engCode = "HG001267";// 工程编号
	private String projectCode = "XM20170385";// 项目编号
	private String baseUlr = "http://szwb.sz.gov.cn:2018";// 请求地址

	/**
	 * 貌似是硬件通用的上传图片接口√
	 */
	public void uploadImage() {
		HashMap<String, Object> paramMap = new HashMap<>();
		// 文件
		File file = new File("C:\\Users\\YS\\Desktop\\downloadImgToWebSiteWeiChat\\timg.jpg");
		paramMap.put("file", file);
		paramMap.put("api_key", api_key);
		String result = HttpUtil.post("https://szwb.sz.gov.cn:2019/uploadfile-openpai/uploadImage", paramMap);
		log.info(result);// 返回文件的id
		// resultData":"ffbe6ac3b17f5a457cbd1a7abfe2ff1e"
	}

	/**
	 * 2.5.2上报环境监测设备基本信息√√
	 *
	 * @return
	 */
	public String addBasicInfo(RequestGongWuShuTspBaseInfo r) {
		String url = baseUlr + "/openapi/envMonitoring/addBasicInfo";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		log.info(timestamp);

		// Map json2 = new HashMap();
		// json2.put("name", "13#新二二四");
		// json2.put("device_installation_date", timestamp);
		// json2.put("install_company", "广东省第一建筑工程有限公司");
		// json2.put("me_option", "jiancexiang");
		// json2.put("device_no", "7986207e559b45a3ab62611c288820a2");
		// json2.put("state", 233);
		// json2.put("type", 1);
		// json2.put("install_address", "某个角落");

		// json2.put("name", "19#测试井");
		// json2.put("device_installation_date", "2020-07-15\n\t\t06:00:00");
		// json2.put("install_company", "福田南华村《一顺科技》");
		// json2.put("device_no", "000000YKDZHJJC000000042200000000");
		// json2.put("type", 1);
		// json2.put("install_address", "没有地点");

		String j2r = JSON.toJSONString(r);
		JSONObject json = JSONObject.parseObject(j2r);
		String body = JSON.toJSONString(json); // 有点变态的逻辑..，真的是要转了又转，为的就是要跟模拟的一个模子刻出来的
		// 2020-12-08

		// String body2 = JSON.toJSONString(json2);
		// log.info("sha:"+body);
		// log.info("xia:"+body2);

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, body);
		// String signature2 = getSignature(api_key, api_version, engCode,
		// projectCode, timestamp, body2);
		log.info("sha:" + signature);
		// log.info("xia:"+signature2);

		String a = GwsLgqUtil.GwsParamUtil(json, timestamp, signature, api_key, projectCode, engCode, api_version);

		log.info("最终请求信息：" + a);

		String info = HttpUtil.post(url, a);
		log.info("down!" + info);
		return info;
	}

	/**
	 * 2.5.3上报环境监测设备基本信息√√
	 * <p>
	 * 通过controller进行上传 可根据不同的项目进行上传到工务署
	 *
	 * @return
	 */
	public String addBasicInfo(String apiKey, String projectCode, String engCode, RequestGongWuShuTspBaseInfo r) {
		String url = baseUlr + "/openapi/envMonitoring/addBasicInfo";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		String j2r = JSON.toJSONString(r);
		JSONObject json = JSONObject.parseObject(j2r);
		String body = JSON.toJSONString(json); // 有点变态的逻辑..，真的是要转了又转，为的就是要跟模拟的一个模子刻出来的
		// 2020-12-08

		String signature = getSignature(apiKey, api_version, engCode, projectCode, timestamp, body);
		log.info("sha:" + signature);

		String a = GwsLgqUtil.GwsParamUtil(json, timestamp, signature, apiKey, projectCode, engCode, api_version);

		log.info("最终请求信息：" + a);

		String info = HttpUtil.post(url, a);

		log.info("down!" + info);

		return info;
	}

	/**
	 * 2.5.1环境监测实时数据√√
	 *
	 * @return 返回info，工务署返回的String结果
	 */
	public String addRecord(RequestGongWuShuTspRealTimeData r) {
		String url = baseUlr + "/openapi/envMonitoring/addRecord";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		JSONObject param = new JSONObject();
		JSONObject body = new JSONObject();
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", timestamp);
		// body.put("board_longitude", 0.0);
		// body.put("pm10", 13);
		// body.put("runtime", "2020-12-04 05:02:59");
		// body.put("device_no", "000000YKDZHJJC000000042200000000");//
		// 根据2.5.2上传的设备号查询
		// body.put("wind_direction", "东");
		// body.put("pressure", 0.0);
		// body.put("voltage", 0.0);
		// body.put("tsp", 17);
		// body.put("board_humidity", 0.0);
		// body.put("pm25", 10);
		// body.put("noise", 0.0);
		// body.put("temperature", 0.0);
		// body.put("humidity", 0.0);
		// body.put("wind_speed", 0.2);
		// body.put("board_latitude", 0.0);
		// body.put("board_temp", 0.0);

		String j2r = JSON.toJSONString(r);
		JSONObject json = JSONObject.parseObject(j2r);

		List<JSONObject> bodyList = new ArrayList<>();// 可以传入多个body
		bodyList.add(json);
		param.put("body", bodyList);// body
		String jsonBody = JSONObject.toJSONString(bodyList);// body的json字符串
		log.info("body:" + jsonBody);
		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, jsonBody);
		param.put("signature", signature);
		// 发送请求
		String info = HttpUtil.post(url, param.toJSONString());
		log.info("最终结果提交：" + param.toJSONString());
		log.info(info);
		return info;

	}

	public static void main(String[] args) {

		String api_key = "08a44b1d310143b7911a3a54d33136b4";
		String api_version = "1.0";
		String engCode = "HG001267";// 工程编号
		String projectCode = "XM20170385";// 项目编号
		String baseUlr = "http://szwb.sz.gov.cn:2018";// 请求地址
		String url = baseUlr + "/openapi/envMonitoring/addRecord";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		JSONObject param = new JSONObject();
		JSONObject body = new JSONObject();
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", timestamp);
		body.put("board_longitude", 0.0);
		body.put("pm10", 13);
		body.put("runtime", "2023-04-28 17:53:59");
		body.put("device_no", "000000YKDZHJJC000000104400000000");// 根据2.5.2上传的设备号查询
		body.put("wind_direction", "东");
		body.put("pressure", 0.0);
		body.put("voltage", 0.0);
		body.put("tsp", 17);
		body.put("board_humidity", 0.0);
		body.put("pm25", 10);
		body.put("noise", 0.0);
		body.put("temperature", 0.0);
		body.put("humidity", 0.0);
		body.put("wind_speed", 0.2);
		body.put("board_latitude", 0.0);
		body.put("board_temp", 0.0);

		String j2r = JSON.toJSONString(body);
		JSONObject json = JSONObject.parseObject(j2r);

		List<JSONObject> bodyList = new ArrayList<>();// 可以传入多个body
		bodyList.add(json);
		param.put("body", bodyList);// body
		String jsonBody = JSONObject.toJSONString(bodyList);// body的json字符串
		log.info("body:" + jsonBody);
		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, jsonBody);
		param.put("signature", signature);
		// 发送请求
		String info = HttpUtil.post(url, param.toJSONString());
		log.info("最终结果提交：" + param.toJSONString());
		log.info(info);
	}

	/**
	 * 2.5.2环境监测实时数据√√
	 *
	 * @return 返回info，工务署返回的String结果
	 */
	public String addRecord(RequestGongWuShuTspRealTimeData r, String apiKey, String projectCode, String engCode,
			String apiVersion) {
		String url = baseUlr + "/openapi/envMonitoring/addRecord";
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		JSONObject param = new JSONObject();
		param.put("api_key", apiKey);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", apiVersion);
		param.put("timestamp", timestamp);
		if (r.getWind_direction() == null) {
			r.setWind_direction("南");
		}
		String j2r = JSON.toJSONString(r);
		JSONObject json = JSONObject.parseObject(j2r);

		List<JSONObject> bodyList = new ArrayList<>();// 可以传入多个body
		bodyList.add(json);
		param.put("body", bodyList);// body
		String jsonBody = JSONObject.toJSONString(bodyList);// body的json字符串
		log.info("body:" + jsonBody);
		if (r.getPm25() >= 50) {
			r.setPm25(40);
		}
		if (r.getPm10() >= 80) {
			r.setPm10(70);
		}
		if (r.getNoise() >= 70) {
			r.setNoise(60.0);
		}
		String signature = getSignature(apiKey, apiVersion, engCode, projectCode, timestamp, jsonBody);
		param.put("signature", signature);
		// 发送请求
		String info = HttpUtil.post(url, param.toJSONString());

		log.info("最终结果提交：" + param.toJSONString());

		log.info("工务署返回值：" + info);

		return info;
	}

	/**
	 * 获取签名
	 *
	 * @param: [apiKey,
	 *             apiVersion, engCode, projectCode, timestamp, body]
	 * @return: java.lang.String
	 */
	// public static String getSignature(String apiKey, String apiVersion,
	// String engCode, String projectCode,
	// String timestamp, String body) {
	// String str4MD5 =
	// String.format("api_key%sapi_version%sbody%seng_code=%sproject_code=%stimestamp%s",
	// apiKey, apiVersion, body.isEmpty() ? "{}" : body, engCode, projectCode,
	// timestamp);
	// log.info(":::"+getMD5Code(str4MD5));
	// return getMD5Code(str4MD5);
	// }
	public static String getSignature(String apiKey, String apiVersion, String engCode, String projectCode,
			String timestamp, String body) {
		String str4MD5 = String.format("api_key%sapi_version%sbody%seng_code=%sproject_code=%stimestamp%s", apiKey,
				apiVersion, body.isEmpty() ? "{}" : body, engCode, projectCode, timestamp);
		return getMD5Code(str4MD5);
	}

	public static String getMD5Code(String strObj) {
		String resultString = null;
		try {
			resultString = new String(strObj);
			MessageDigest md = MessageDigest.getInstance("MD5");
			Charset charset = Charset.forName("UTF-8");
			resultString = byteToString(md.digest(strObj.getBytes(charset)));
		} catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}
		return resultString;
	}

	// 转换字节数组为16进制字串
	private static String byteToString(byte[] bByte) {
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < bByte.length; i++) {
			sBuffer.append(byteToArrayString(bByte[i]));
		}
		return sBuffer.toString();
	}

	private static String byteToArrayString(byte bByte) {
		int iRet = bByte;
		if (iRet < 0) {
			iRet += 256;
		}
		int iD1 = iRet / 16;
		int iD2 = iRet % 16;
		return strDigits[iD1] + strDigits[iD2];
	}

	// 全局数组
	private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D",
			"E", "F" };

}
